package com.atguigu.dga.meta.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.dga.meta.bean.TableMetaInfo;
import com.atguigu.dga.meta.bean.TableMetaInfoExtra;
import com.atguigu.dga.meta.bean.TableMetaInfoForQuery;
import com.atguigu.dga.meta.bean.TableMetaInfoVO;
import com.atguigu.dga.meta.service.TableMetaInfoExtraService;
import com.atguigu.dga.meta.service.TableMetaInfoService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 元数据表 前端控制器
 * </p>
 *
 * @author zhangjunyi
 * @since 2023-06-03
 */
@RestController
@RequestMapping("/tableMetaInfo")
public class TableMetaInfoController {


    @Autowired
    TableMetaInfoService tableMetaInfoService;

    @Autowired
    TableMetaInfoExtraService tableMetaInfoExtraService;

    @PostMapping("init-tables/{dataBaseName}/{assessDate}")
    public String initTables(@PathVariable("dataBaseName") String dataBaseName, @PathVariable("assessDate") String assessDate) {
        tableMetaInfoService.initMetaInfo(assessDate,dataBaseName);
        return "success";
    }

    @GetMapping("table-list")
    public String tableList(TableMetaInfoForQuery tableMetaInfoForQuery){
        List<TableMetaInfoVO> tableMetaInfoList = tableMetaInfoService.getTableMetaInfoList(tableMetaInfoForQuery);

        Integer count = tableMetaInfoService.getTableMetaInfoCount(tableMetaInfoForQuery);

        JSONObject jsonObj = new JSONObject();
        jsonObj.put("total", count);
        jsonObj.put("list", tableMetaInfoList);

        return jsonObj.toJSONString();
    }


    @GetMapping("table/{id}")
    public String tableDetail(@PathVariable("id") String tableId){
        //1.先查询TableMetaInfo表数据  根据tableId查询
        TableMetaInfo tableMetaInfo = tableMetaInfoService.getOne(new QueryWrapper<TableMetaInfo>().eq("id", tableId));
//        TableMetaInfo tableMetaInfo = tableMetaInfoService.getById(tableId);

        //2.根据已有的库名和表名获取到辅助信息表的数据
        TableMetaInfoExtra tableMetaInfoExtra = tableMetaInfoExtraService.getOne(new QueryWrapper<TableMetaInfoExtra>().eq("table_name", tableMetaInfo.getTableName()).eq("schema_name", tableMetaInfo.getSchemaName()));

        tableMetaInfo.setTableMetaInfoExtra(tableMetaInfoExtra);

        //将对象转为JSON字符串
        String jsonString = JSON.toJSONString(tableMetaInfo);

        System.out.println(jsonString);

        return jsonString;
    }


    @PostMapping("tableExtra")
    public String tableExtra(@RequestBody TableMetaInfoExtra tableMetaInfoExtra){
//        tableMetaInfoExtraService.saveOrUpdate(tableMetaInfoExtra)

        //设置更新时间
        tableMetaInfoExtra.setUpdateTime(new Date());

        //将数据更新到Mysql库中
        tableMetaInfoExtraService.updateById(tableMetaInfoExtra);

        return "success";
    }
}
